<?php

function __autoload($classname){
	$dir = dirname(__FILE__);
	if(is_file("$dir/$classname.php")) include("$dir/$classname.php");
	else include("$dir/curlm/$classname.php");
}

function sigterm_main_handler($signo) {
	global $pid;
	if($signo == SIGTERM) {
		foreach($g_pids as $pid) {
			posix_kill($pid, SIGTERM);
 		}
	}
}

function sigterm_worker_handler($signo) {
	global $g_worker_stop;
	if($signo == SIGTERM) {
		$g_worker_stop = 1;
	}
}

function worker_do() {
	global $opt_concurrency, $opt_requests , 
		$g_workers_count , 
		$g_main_pid ,
		$g_main_msgtype,
		$g_worker_msgtype,
		$g_worker_pid ,
		$g_worker_stop ,
		$g_curl_opts,
		$opt_url 
		;

	$g_worker_pid = posix_getpid();
	pcntl_signal(SIGTERM, "sigterm_worker_handler");

	$tunnel_count = ceil($opt_concurrency / $g_workers_count);
	$requests_per_worker = floor($opt_requests / $g_workers_count) ;

	$msg = new ProcMessage($g_main_pid);

	//echo "pid: $g_worker_pid init \n";

	$tasklist = new CurlTaskList();

	//make tasks
	for($i=0; $i<$requests_per_worker; $i++) {
		$tasklist->push(new ABCurlTask($opt_url, $g_curl_opts));
	}

	$curlm = new CurlMFetcher($tasklist, $tunnel_count);
	//$curlm->setDebug(true);

	//send to main process , i'm readly
	$msg->send('readly', $g_main_msgtype);

	//wait for main process signal 
	while(1) {
	 	$r = $msg->receive($g_worker_msgtype);
		if(empty($r)){
	 		usleep(1000);
			continue;
		}

		if($r['data'] == 'begin') break;
	}

	$begin_time = microtime(1);

	//run
	$curlm->run();

	$end_time = microtime(1);

	//end and analyze
	$stat = array(
		'tunnels'	=>  $tunnel_count ,
		'number'	=>	$tasklist->count() ,
		'begin_time'=>  $begin_time ,
		'end_time'	=>  $end_time ,
		'http_code_2xx' => 0 ,
		'http_code_non_2xx' => 0 ,
		'connect_total' => 0 ,
		'connect_min'	=> 100000 ,
		'connect_max'	=> 0 ,
		'request_total' => 0 ,
		'request_min'	=> 100000 ,
		'request_max'	=> 0 ,
		);
	$tasklist->rewind();
	do {
		$current = $tasklist->current();
		$info = $current->getInfo();

		if($info['http_code'] >= 200 && $info['http_code'] < 300) {
			$stat['http_code_2xx'] ++;
		}
		else {
			$stat['http_code_non_2xx'] ++;
		}

		$stat['connect_total'] += $info['connect_time'] ;
		if($info['connect_time'] < $stat['connect_min']) {
			$stat['connect_min'] = $info['connect_time'];
		}
		if($info['connect_time'] > $stat['connect_max']) {
			$stat['connect_max'] = $info['connect_time'];
		}

		$stat['request_total'] += $info['total_time'] ;
		if($info['total_time'] < $stat['request_min']) {
			$stat['request_min'] = $info['total_time'];
		}
		if($info['total_time'] > $stat['request_max']) {
			$stat['request_max'] = $info['total_time'];
		}
	}
	while($tasklist->next());

	$stat['Requests per second'] = $stat['number'] / ($stat['end_time'] - $stat['begin_time'] );

	//send to main process , finished 
	$msg->send(array('stat', $stat), $g_main_msgtype);

	exit(0);
}
